/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Form, Input, Row, Col } from 'antd';
import { connect } from 'dva';
import KbModal from '@/components/KbModal';
import KbIcon from '@/components/KbIcon';
import Captcha from '@/components/Captcha';
import { names } from '../../config';
import KbChildrenWrapper from '@/components/KbChildrenWrapper';

const { Item: FormItem } = Form;

@connect(({ loading }) => ({
  getting: loading.effects['source/getCaptcha'],
  authing: loading.effects['source/auth'],
  matching: loading.effects['source/getCourierInfo'],
}))
@Form.create()
class Courier extends Component {
  static defaultProps = {
    onAdded: () => {},
  };
  constructor(props) {
    super(props);
    this.state = {
      courierLable: '',
      courierData: null,
      visible: false,
    };
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  //   打开或关闭指定弹窗
  onTriggerModal = open => {
    this.setState({
      visible: open,
    });
  };

  // 获取验证码
  onGetCaptcha = () => {
    return new Promise((resolve, reject) => {
      const { dispatch, form } = this.props;
      form.validateFields(['courier_no'], err => {
        if (err) {
          this.setState({
            courierLable: err.courier_no.errors[0].message,
          });
          return;
        }
        const { courierPhone: courier_phone, courierNo: courier_no, brand } =
          this.state.courierData || {};
        if (courier_phone) {
          dispatch({
            type: 'source/getCaptcha',
            payload: {
              brand,
              courier_phone,
              courier_no,
            },
          })
            .then(resolve)
            .catch(reject);
        }
      });
    });
  };

  // 提交
  onOk = () => {
    const { form, dispatch, onAdded } = this.props;
    form.validateFields({ first: true }, (err, values) => {
      const { courierData } = this.state;
      if (!courierData) {
        this.setState({
          courierLable: err.courier_no.errors[0].message,
        });
        return;
      }
      if (err) {
        return;
      }
      const { brand, courierPhone: courier_phone } = courierData;
      dispatch({
        type: 'source/auth',
        payload: {
          brand,
          courier_phone,
          ...values,
        },
        kind: 'courier',
      }).then(({ code }) => {
        if (code == 0) {
          this.setState(
            {
              courierData: null,
              courierLable: '',
            },
            () => {
              this.onTriggerModal(false);
              form.resetFields();
              onAdded();
              dispatch({
                type: 'source/getCourier',
              });
            },
          );
        }
      });
    });
  };

  // 根据工号匹配快递员
  matchCourier = e => {
    const { value: courier_no } = e.target;
    clearTimeout(this.timer);
    if (courier_no) {
      const { dispatch } = this.props;
      this.timer = setTimeout(() => {
        dispatch({
          type: 'source/getCourierInfo',
          payload: {
            courier_no,
          },
        }).then(res => {
          const { code, data, msg } = res;
          const courierData = code == 0 && data ? data : null;
          this.setState({
            courierData,
            courierLable: !courierData ? msg : `${courierData.showPhone} ${courierData.courierNo}`,
          });
        });
      }, 100);
    } else {
      this.setState({
        courierData: null,
        courierLable: '',
      });
    }
  };

  render() {
    const { visible, courierLable, courierData } = this.state;
    const { children, form, getting, authing, matching } = this.props;
    return (
      <>
        <KbChildrenWrapper className="pointer" onClick={this.onTriggerModal.bind(this, true)}>
          {children}
        </KbChildrenWrapper>
        <KbModal
          loading={!!matching}
          visible={visible}
          onCancel={this.onTriggerModal.bind(this, false)}
          title={names.courier.label}
          okText="提交"
          onOk={this.onOk}
          okButtonProps={{ loading: authing, disabled: matching || !courierData }}
          footer={
            <div className="kb-tips">
              <div className="kb-tips_title">添加须知</div>
              <div className="kb-tips_item">获取巴枪工号授权后可用来进行打单操作</div>
              <div className="kb-tips_item">申通：授权工号必须开通获取77单号的权限</div>
              <div className="kb-tips_item">中通：授权工号必须在掌中通后台开通获取单号的权限</div>
              <div className="kb-tips_item">
                请输入包含网点编号的完整快递员工号，申通为10位数字，如：5200130010。中通为以.连接的8-9位数字，如：02163.811
              </div>
            </div>
          }
        >
          <Form>
            <FormItem
              help={courierLable}
              validateStatus={courierLable && !courierData ? 'error' : 'success'}
            >
              {form.getFieldDecorator('courier_no', {
                rules: [
                  {
                    required: true,
                    message: '请输入快递员工号',
                  },
                ],
              })(
                <Input
                  size="large"
                  maxLength={20}
                  prefix={<KbIcon type="user" style={{ color: '#999' }} />}
                  placeholder="请输入快递员工号（支持申通、中通）"
                  onChange={this.matchCourier}
                />,
              )}
            </FormItem>
            <FormItem help="">
              <Row gutter={8}>
                <Col span={16}>
                  {form.getFieldDecorator('sms_code', {
                    rules: [
                      {
                        required: true,
                        message: '请输入快递员收到的验证码',
                      },
                    ],
                  })(
                    <Input
                      size="large"
                      maxLength={10}
                      prefix={<KbIcon type="safety" style={{ color: '#999' }} />}
                      placeholder="请输入快递员收到的验证码"
                    />,
                  )}
                </Col>
                <Col span={8}>
                  <Captcha
                    size="large"
                    loading={getting}
                    style={{ width: '100%' }}
                    type="primary"
                    ghost
                    onGetCaptcha={this.onGetCaptcha}
                  >
                    获取验证码
                  </Captcha>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </KbModal>
      </>
    );
  }
}

export default Courier;
